package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.kaishengit.entity.Project;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.Page;
import com.kaishengit.util.db.RowMapper;

public class ProjectDao {

	private DBHelp<Project> db = new DBHelp<Project>();
	
	public void save(Project p) {
		String sql = "insert into t_project(id,name,desc) values(?,?,?)";
		db.executeQuery(sql, p.getId(),p.getName(),p.getDesc());
	}
	
	public List<Project> findAll() {
		String sql = "select id,name,desc,createtime from t_project order by createtime";
		return db.executeQueryToList(sql, new ProjectRowMapper());
	}
	 
	public Page<Project> findByUserIdAndPageNum(String userId,int pageNum) {
		Page<Project> page = new Page<Project>(count(),pageNum);
		
		StringBuilder sql = new StringBuilder();
		sql.append("select tp.id,tp.name,tp.desc,createtime from t_project as tp ");
		sql.append("left join t_user_project as tup on tup.projectid = tp.id ");
		sql.append("left join t_user as tu on tup.userid = tu.id where tu.id = ? limit ?,?");
		List<Project> list = db.executeQueryToList(sql.toString(), new ProjectRowMapper(),userId,page.getStart(),page.getPageSize());
		page.setList(list);
		return page;
	}
	 
	public Project findById(String id) {
		String sql = "select id,`name`,`desc`,createtime from t_project where id = ?";
		return db.executeQueryToObject(sql, new ProjectRowMapper(), id);
		
	}
	private int count() {
		String sql = "select count(*) from t_project";
		return db.executeQuery(sql).intValue();
	}

	public class ProjectRowMapper implements RowMapper<Project> {

		public Project mapRow(ResultSet rs) throws SQLException {
			
			List<Project> list = new ArrayList<Project>();
			
			Project p = new Project();
			p.setId(rs.getString("id"));
			p.setName(rs.getString("name"));
			p.setDesc(rs.getString("desc"));
			p.setCreatetime(rs.getString("createtime"));
			list.add(p);
			
			return p;
		}
		
	}
}
